var $soaFileUtils = {
    // 从JSP页面动态注入url值
    formatFileSize: function (bytes) {
        if (bytes === 0)
            return '0 B';
        var k = 1024;
        sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        i = Math.floor(Math.log(bytes) / Math.log(k));
        var num = bytes / Math.pow(k, i);
        return num.toFixed(1) + ' ' + sizes[i];
        // return (bytes / Math.pow(k, i)) + ' ' + sizes[i];
        // toPrecision(3) 后面保留一位小数，如1.0GB //return (bytes / Math.pow(k,
        // i)).toPrecision(3) + ' ' + sizes[i];
    },
    error_waitShow_flag: false,
    formatFileType: function (type) {
        return type;
    },
    setErrorFlag: function () {
        $soaFileUtils.error_waitShow_flag = true;
        setTimeout(function () {
            $soaFileUtils.error_waitShow_flag = false
        }, 2000);
    }

}
//默认url
// var fileServiceUrl="https://127.0.0.1:1443/";
$soaFileUtils.fileServiceUrl="";

// if ("undefined" != typeof $soa_fileServiceUrl) {
//     $soaFileUtils.fileServiceUrl = $soa_fileServiceUrl;
// }

    var webUploader = new Array();


    (function ($) {

        $.fn
            .extend({
                // 文件上传
                soaUploader: function (options) {
                    console.log(options);
                    $soaFileUtils.fileServiceUrl =options.server;
                    console.log( $soaFileUtils.fileServiceUrl);
                    $soaFileUtils.uploadUrl = $soaFileUtils.fileServiceUrl + '/file/uploadDfs',
                    $soaFileUtils.md5CheckUpload = $soaFileUtils.fileServiceUrl + '/file/md5CheckUpload',
                    $soaFileUtils.downloadUrl =  '/file/download',
                    $soaFileUtils.downloadPackageUrl =  '/file/downloadPackage',
                    $soaFileUtils.preview = '/file/preview',

                    $soaUploader = $(this);
                    var settings = {
                        url: $soaFileUtils.uploadUrl,
                        fileType: "media",
                        fileName: "file",
                        data: {},
                        swf: '/common/fileUpLoad/js/Uploader.swf',
                        maxSize: 500,
                        extensions: null,
                        before: null,
                        complete: null,                        
                        fileNumLimit: null,// 验证文件总数量, 超出则不允许加入队列
                        fileSizeLimit: null,// 验证文件总大小是否超出限制,
                        // 超出则不允许加入队列。
                        fileSingleSizeLimit: null,// 验证单个文件大小是否超出限制,
                        // 超出则不允许加入队列
                        PostbackHold: false,
                        auto: false,
                        prepareNextFile: true,
                        //去重， 根据文件名字、文件大小和最后修改时间来生成hash Key
                        //true为可重复   ，false为不可重复
                        duplicate:true
                    };
                    $.extend(settings, options);
                    console.log(options);
                    console.log(settings);
                    settings.extensions = '*';
                    // 特殊处理 文件上传类型
                    if (!settings.accept) {
                        // 默认的上传类型
                        settings.accept = {
                            extensions: settings.extensions
                        };
                    }
                    // var $hiddenInput = $('#UploadhiddenInput');

                    // 先注销再注册
                    WebUploader.Uploader
                        .unRegister("lei_before_send_file");
                    // 注册上传功能
                    WebUploader.Uploader
                        .register({
                            name: 'lei_before_send_file',
                            "before-send-file": function (file,
                                                          formData) {
                                var task = new $.Deferred();
                                settings.webUploader
                                    .md5File(file, 0,
                                        15 * 1024 * 1024)
                                    .then(
                                        function (val) {
                                            $
                                                .ajax(
                                                    {
                                                        type: "GET",
                                                        url: $soaFileUtils.md5CheckUpload,
                                                        data: {
                                                            md5: val,
                                                            fileSize: file.size,
                                                            userId: settings.userId,
                                                            moduleName: settings.moduleName,
                                                            fileSrcName: file.name
                                                            // 后台接收
                                                            // String
                                                            // md5
                                                        },
                                                        cache: false,
                                                        timeout: 3000,
                                                        dataType: "json",
                                                        crossDomain: true == !(document.all)
                                                    })
                                                .then(
                                                    function (
                                                        data,
                                                        textStatus,
                                                        jqXHR) {
                                                        if (data.message == 0) { // 若存在，这返回失败给WebUploader，(后台操作)表明该文件不需要上传，然后就可以把数据库查询出的文件信息的物理路径给新文件
                                                            task
                                                                .reject(); //
                                                            settings.webUploader
                                                                .skipFile(file);
                                                            // setTableBtn(file.id,'秒传');
                                                            // element.progress(file.id,
                                                            // '100%');
                                                            if (settings.onUploadSuccess) {
                                                                if (typeof settings.onUploadSuccess == "function") {
                                                                    if (settings.onUploadProgress) {
                                                                        if (typeof settings.onUploadProgress == "function") {
                                                                            settings
                                                                                .onUploadProgress(
                                                                                    file,
                                                                                    1);
                                                                        }
                                                                    }
                                                                	settings
                                                                        .onUploadSuccess(
                                                                            file,
                                                                            data);
                                                                }
                                                            }
                                                             /*特殊方法
                                                             支持自定义参数*/
                                                            if (settings.onUploadSuccessFnStr) {
                                                                var tempFn = wings_getFunc(settings.onUploadSuccessFnStr);
                                                                for (var b = 0; b < tempFn.length; b++) {
                                                                    var func = eval(tempFn[b]);
                                                                    if (typeof func == "function") {
                                                                        var result = func(
                                                                            file,
                                                                            data);
                                                                    }
                                                                }
                                                                ;
                                                            }
                                                            // $("#hiddenInput"
                                                            // +
                                                            // $(item)[0].id
                                                            // +
                                                            // file.id).val(data.url);
                                                        } else {
                                                            // WingsDialog.alert(
                                                            // settings.webUploader.options.formData);
                                                            settings.webUploader.options.formData = {
                                                                md5: val,
                                                                fileSize: file.size,
                                                                userId: settings.userId,
                                                                moduleName: settings.moduleName
                                                            };
                                                            // WingsDialog.alert(
                                                            // settings.webUploader.options.formData);
                                                            task
                                                                .resolve();
                                                        }
                                                    },
                                                    function (
                                                        jqXHR,
                                                        textStatus,
                                                        errorThrown) {
                                                        // 任何形式的验证失败，都触发重新上传
                                                        task
                                                            .resolve();
                                                    });
                                        });
                                return $.when(task);
                            }
                        });

                    var element = this;
                    var $element = $(element);
                    settings.webUploader = WebUploader
                        .create(
                            {
                                server: settings.url
                                    + (settings.url
                                        .indexOf('?') < 0 ? '?'
                                        : '&')
                                    + 'fileType='
                                    + settings.fileType
                                    + '&token=',
                                // 如果单个文件自动上传
                                // 在传参是建议把multiple设置成false禁止多选文件
                                pick: {
                                    id: element,
                                    multiple: settings.multiple == false ? false
                                        : true
                                },
                                onAllComplete: function (event) {
                                    //全部完成的回调函数
                                   if (settings.onAllComplete) {
                                       if (typeof settings.onAllComplete == "function") {
                                           settings
                                               .onAllComplete(
                                                   event);
                                       }
                                   }

                               },
                                swf: '/common/fileUpLoad/js/Uploader.swf',
                                fileVal: settings.fileName,
                                formData: settings.data,
                                fileSingleSizeLimit: settings.maxSize * 1024 * 1024,
                                accept: settings.accept,
                                // 如果单个文件自动上传
                                // 在传参阶段是建议把fileNumLimit设置成1即文件队列里只能有一个待上传文件
                                fileNumLimit: 80,
                                threads: 1,
                                resize: false,
                                prepareNextFile: true,
                                //去重， 根据文件名字、文件大小和最后修改时间来生成hash Key
                                //true为可重复   ，false为不可重复
                                duplicate:true
                            })
                        .on(
                            'beforeFileQueued',
                            function (file) {
                                if ($
                                        .isFunction(settings.before)
                                    && settings.before
                                        .call(element,
                                            file) === false) {
                                    return false;
                                }
                                if (settings.extensions == ''
                                    || file.ext == ''
                                    || file.ext == 'exe'
                                    || file.ext == 'xml'
                                    || file.ext == 'bat') {
                                    this.trigger('error',
                                        'Q_TYPE_DENIED');
                                    return false;
                                }
                                
                                // this.reset();

                                // console.log($element.parent("div").prev("div").attr("class"));
                                // $progressBar.show();
                            })
                        .on(
                            'fileQueued',
                            function (file) {
                                // 【lei】 在这里选择文件之后
                                // 文件选择成功后的回调函数
                                var t_res = '';
                                if (settings.onFileQueued) {
                                    if (typeof settings.onFileQueued == "function") {
                                        // 根据返回值，是否组织上传
                                        t_res = settings
                                            .onFileQueued(file);
                                    }
                                }
                                // 自动上传
                                if (settings.auto == true
                                    && t_res != "false") {
                                    this.upload();
                                }

                            })
                        .on(
                            'uploadProgress',
                            function (file, percentage) {
                                // 【lei】进度条
                                // var $li = $('#' +
                                // $element.attr('id').substring(0,8)
                                // + file.id),
                                //
                                // $percent =
                                // $li.find('.progress .bar');
                                // //$li.find('.progress
                                // .bar').html('上传中');
                                // $li.find(".progress
                                // .percentage
                                // .text").text(Math.round(percentage
                                // * 100) + '%');
                                // $percent.css('width',
                                // percentage * 100 + '%');

                            	if(percentage==1){
                            		percentage=0.99;
                            	}
                                // 文件选择成功后的回调函数
                                if (settings.onUploadProgress) {
                                    if (typeof settings.onUploadProgress == "function") {
                                        settings
                                            .onUploadProgress(
                                                file,
                                                percentage);
                                    }
                                }

                            })
                        .on(
                            'uploadAccept',
                            function (file, data) {
                                // $progressBar.fadeOut("slow",
                                // function() {
                                // $progressBar.width(0);
                                // });
                                // if (data.message.type !=
                                // 'success') {
                                // WingsDialog.alert(data.message);
                                // return false;
                                // }
                                if ($
                                    .isFunction(settings.complete)) {
                                    settings.complete
                                        .call(element,
                                            file, data);
                                }
                            })
                        .on('uploadSuccess', function (file, data) {
                             //【lei】 上传成功回调放法
                             //文件选择成功后的回调函数
                             if(settings.onUploadSuccess){
                             if (typeof settings.onUploadSuccess
                             == "function") {
                             settings.onUploadSuccess(file, data);
                             }
                             }

                        })
                        .on('fileDequeued', function (file) {

                            // =====================================================
                            // var fullName = $("#hiddenInput" +
                            // $element.attr('id').substring(0,8) +
                            // file.id).val();
                            // if (fullName!=null) {删除服务器文件
                            // $.post(webuploaderoptions.deleteServer,
                            // { fullName: fullName }, function
                            // (data) {
                            // WingsDialog.alert(data.message);
                            // })
                            // }
                            // $("#"+
                            // $element.attr('id').substring(0,8) +
                            // file.id).remove();
                            // $("#hiddenInput" +
                            // $element.attr('id').substring(0,8) +
                            // file.id).remove();
                            // =====================================================

                        })
                        .on(
                            'error',
                            function (type) {
                                if ($soaFileUtils.error_waitShow_flag == false) {
                                    // 可以显示
                                    switch (type) {
                                        case "F_DUPLICATE":
                                            WingsDialog
                                                .alert("请不要重复上传文件！");
                                            // $soaFileUtils
                                            //     .setErrorFlag();
                                            break;
                                        case "F_EXCEED_SIZE":
                                            WingsDialog
                                                .alert("上传文件过大，请重新选择！");
                                            // $soaFileUtils
                                            //     .setErrorFlag();
                                            break;
                                        case "Q_TYPE_DENIED":
                                            if (settings.typeErrMsg) {
                                                WingsDialog
                                                    .alert(settings.typeErrMsg);
                                            } else {
                                                WingsDialog
                                                    .alert("不能上传xml、exe、bat等文件！");
                                            }
                                            // $soaFileUtils
                                            //     .setErrorFlag();
                                            break;
                                        default:
                                            WingsDialog
                                                .alert("上传文件出现错误!//r//n错误码："
                                                    + type
                                                    + "。");
                                            // $soaFileUtils
                                            //     .setErrorFlag();
                                    }
                                }
                            });

                    $soaUploader.opts = settings;
                    // 删除文件
                    $soaUploader.removeFile = function (fileId) {
                        // var file = settings.webUploader.getFile(id);
                        settings.webUploader.removeFile(fileId);
                    }

                    // 文件提交
                    $soaUploader.upload = function () {
                        return settings.webUploader.upload();
                    };

                    return $soaUploader;

                }

            });

    })(jQuery);


//===========追加圆形进度条================
var szoa_fileLoading_opt = {
		baseColor:'#D1D3D7',//'#D1D3D7'
		showColor:'#00A5E0',//#00A5E0'
		width:20,
		height:20,
		r:15
	}

/**
 * 在divId处创建圆形进度条
 * @param {Object} divId
 */
function szoa_fileLoadingCreat(divId){
	var $ths = $('#'+divId);
	if(!$ths) return;
	
//	var tempStr = '<svg class="svgShow" viewbox="0 0 40 40">'
//		+' 	<circle cx="20" cy="20" r="15" stroke-width="3" stroke="#D1D3D7" fill="none"></circle>'
//		+' 	<circle cx="20" cy="20" r="15" stroke-width="3" stroke="#00A5E0" fill="none" transform="matrix(0,-1,1,0,0,40)" stroke-dasharray="0 1069"></circle>'
//		+' </svg>'
//		+' <span class="numShow">0</span>';
		
	var tempStr = '<div class = "szoa_svg_loading">' 
		+'<svg class="svgShow" viewbox="0 0 '+(szoa_fileLoading_opt.width * 2)+' '+(szoa_fileLoading_opt.height * 2)+'">'
		+' 	<circle cx="'+szoa_fileLoading_opt.width +'" cy="'+szoa_fileLoading_opt.height +'" r="'+szoa_fileLoading_opt.r +'" stroke-width="3" '
		+' stroke="'+szoa_fileLoading_opt.baseColor+'" fill="none"></circle>'
		+' 	<circle cx="'+szoa_fileLoading_opt.width +'" cy="'+szoa_fileLoading_opt.height +'" r="'+szoa_fileLoading_opt.r +'" stroke-width="3" ' 
		+' stroke="'+szoa_fileLoading_opt.showColor+'" fill="none" ' 
		+' transform="matrix(0,-1,1,0,0,'+(szoa_fileLoading_opt.height * 2)+')" stroke-dasharray="0 1069"></circle>'
		+' </svg>'
		+' <span class="numShow">0</span>'
		+' </div>';
		
	//清空其他
	$ths.empty();
	$ths.append(tempStr);
}

 /**
  * 显示进度，num为0~100 的数字
  * @param {Object} divId
  * @param {Object} num
  * @return {TypeName} 
  */
function szoa_fileLoadingUpload(divId,num){
	var $ths = $('#'+divId);
	if(!$ths) return;
	
    var percent = num / 100, perimeter = Math.PI * 2 * szoa_fileLoading_opt.r;
    //circle = document.querySelectorAll("circle")[1];
    //circle.setAttribute('stroke-dasharray', perimeter * percent + " " + perimeter * (1- percent));
    //设置“圈”
    var  $circle = $ths.find('circle')[1];
    $circle.setAttribute('stroke-dasharray', perimeter * percent + " " + perimeter * (1- percent));
	//设置数
    var  $num = $ths.find('span.numShow').html(num);
	
}

/**
 * 销毁进度条
 * @param {Object} divId
 * @return {TypeName} 
 */
function soa_fileLoadingDestroy(divId){
	var $ths = $('#'+divId);
	if(!$ths) return;
	//清空其他
	$ths.empty();
}
